package crypto

import (
	"crypto/x509"
	"encoding/pem"
	"fmt"
)

//Sign 签名
func Sign(data []byte, privkey PrivateKey) ([]byte, error) {
	return privkey.Sign(data)
}

//Verify 验签
func Verify(data []byte, signature []byte, publicKey PublicKey) (bool, error) {
	return publicKey.Verify(data, signature)
}

//CertFromBytes 证书文件[]byte转对象
func CertFromBytes(buf []byte) (*x509.Certificate, error) {
	block, _ := pem.Decode(buf)
	if block == nil {
		return nil, fmt.Errorf("decode cer failed")
	}
	cert, err := x509.ParseCertificate(block.Bytes)
	if err != nil {
		return nil, fmt.Errorf("parse cer failed")
	}
	return cert, nil
}

//CheckSignatureFrom 验证签发机构
func CheckSignatureFrom(parentBuf []byte, childBuf []byte) (bool, error) {
	blockParent, _ := pem.Decode(parentBuf)
	blockChild, _ := pem.Decode(childBuf)
	if blockChild == nil || blockParent == nil {
		return false, fmt.Errorf("decode cer failed")
	}
	parent, err := x509.ParseCertificate(blockParent.Bytes)
	if err != nil {
		return false, fmt.Errorf("parse parent cer failed")
	}
	child, err := x509.ParseCertificate(blockChild.Bytes)
	if err != nil {
		return false, fmt.Errorf("parse child cer failed")
	}
	err = parent.CheckSignature(child.SignatureAlgorithm, child.RawTBSCertificate, child.Signature)
	if err == nil {
		return true, nil
	}
	return false, err
}
